# -*- coding:utf-8 -*-
import uuid
import os
from werkzeug import secure_filename
from flask import jsonify
from flask import g
from . import api

# from . import auth
from ..api_auth import auth
from ..api_auth import create_token
from ..models import db
from ..models.User import User
from ..models.blog import Post
from ..models.User import users_schema
from ..models.User import user_schema
from ..models.blog import posts_schema
from ..models.blog import post_schema


@api.route('/post/')
def post():
    posts = Post.query.all()

    return posts_schema.jsonify(posts)


@api.route('/post/<id>')
def post_detail(id):
    id = 1
    post = Post.query.filter_by(id=id).first()
    return post_schema.jsonify(post)


ALLOWED_EXTENSIONS = set(['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@api.route('/img_upload', methods=['POST'])
@auth.login_required
def image_upload():
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        filename = str(uuid.uuid4()) + filename.split('.')[-1:][0]
        file.save(os.path.join(os.path.abspath(
            '.') + '/static/img_uploads', filename))
        return filename
    else:
        return 404


@api.route('/test/')
@auth.login_required
def test_auth():
    return jsonify({'message': "Hello, %s!" % g.user})


@api.route('/login/', methods=['POST'])
def login():
    name = 'admin'
    password = '123456'
    result = db.session.query(User).filter(User.username == name).first()
    if result and result.check_password(password):
        token_ = create_token(result.id)
        print token_
        return jsonify({'state': 'success', 'message': 'success', 'data': {'token': token_, 'expires_in': 3600}})
    else:
        return jsonify({'state': 'error', 'message': 'error'})


@api.route('/register/', methods=['POST'])
def register():
    return 'message'
